<?php

namespace plugin\ycMassage\app\model;

use app\common\service\UploadService;
use app\common\utils\Password;
use loong\oauth\facade\Auth;
use plugin\ycMassage\utils\enum\Examine;
use plugin\ycMassage\utils\enum\Gender;
use plugin\ycMassage\utils\enum\State;
use plugin\ycMassage\utils\enum\UserPermissions;
use think\facade\Db;

class MassageUser extends Model
{
    public static function onAfterRead($model)
    {
        if ($model->birthday) {
            $time = time();
            $age = strtotime($model->birthday);
            $model->age = floor(($time - $age) / 31536000);
        }
        if ($model->gender) {
            $model->gender_text = Gender::getText($model->gender)['text'];
        }
    }
    public function setPasswordAttr($value)
    {
        return Password::passwordHash($value);
    }
    public function getNicknameAttr($value)
    {
        return base64_decode($value);
    }
    protected function setNicknameAttr($value)
    {
        return base64_encode($value);
    }
    public function getHeadimgAttr($value)
    {
        # 判断是否为url
        if (strpos($value, 'http') === 0) {
            return $value;
        }
        return $value ? UploadService::url($value) : '';
    }
    public static function getInfo($uid)
    {
        $field = [
            'user.id,user.headimg,user.nickname,user.mobile,user.saas_appid,user.last_login_ip,user.last_login_time,user.birthday,user.gender,user.state',
            'vip.vip_id,vip.vip_time,vip.vip_state',
            'wechat.openid,wechat.mp_openid,wechat.unionid,wechat.nickname as wechat_nickname,wechat.headimg as wechat_headimg,wechat.subscribe',
            'wallet.money,wallet.money_sum,wallet.integral,wallet.integral_sum,wallet.technician_money,wallet.technician_freeze_money,wallet.technician_money_sum,wallet.agent_money,wallet.agent_freeze_money,wallet.agent_money_sum',
            'wallet.dealer_money,wallet.dealer_freeze_money,wallet.dealer_money_sum,wallet.channels_money,wallet.channels_freeze_money,wallet.channels_money_sum,wallet.salesman_money,wallet.salesman_freeze_money,wallet.salesman_money_sum',
        ];
        $model = self::alias('user')->where(['user.id' => $uid])
            ->join('massage_user_vip vip', 'vip.uid = user.id', 'left')
            ->join('massage_user_wechat wechat', 'wechat.uid = user.id', 'left')
            ->join('massage_user_wallet wallet', 'wallet.uid = user.id', 'left')
            ->field($field)
            ->find();
        if (!$model) {
            throw new \Exception('用户不存在', 12000);
        }
        if ($model->state === State::NO['value']) {
            throw new \Exception('该用户已被冻结', 12000);
        }
        $model->token = self::getToken($model);
        $model->vip_title = '';
        if ($model->vip_state) {
            $MassageVipMember = MassageVip::where(['id' => $model->vip_id])->find();
            $model->vip_title = $MassageVipMember->title;
            if ($model->vip_time) {
                $startTime = time();
                $endTime = strtotime($model->vip_time);
                $model->days_remaining = ceil(($endTime - $startTime) / 86400);
            } else {
                $model->days_remaining = 0;
            }
        }
        # 创建钱包账户
        if ($model->money === null) {
            $MassageUserWallet = new MassageUserWallet();
            $MassageUserWallet->saas_appid = $model->saas_appid;
            $MassageUserWallet->uid = $model->id;
            $MassageUserWallet->save();
            $model->money = 0;
            $model->money_sum = 0;
            $model->integral = 0;
            $model->integral_sum = 0;
        }
        $permissions = [];
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $model->id, 'examine' => Examine::YES['value']])->find();
        if ($MassageUserTechnician) {
            $permissions[] = UserPermissions::TECHNICIAN['value'];
            if ((!$MassageUserTechnician->work_mch_id && !$MassageUserTechnician->work_shop_id)||getHpConfig('allow_technician_scheduling',$model->saas_appid,'mch')) {
                $permissions[] = UserPermissions::SCHEDULING['value'];
            }
        }
        if (MassageUserAgent::where(['uid' => $model->id, 'state' => State::YES['value']])->count()) {
            $permissions[] = UserPermissions::AGENT['value'];
        }
        if(MassageUserChannels::where(['uid' => $model->id, 'state' => State::YES['value']])->count()){
            $permissions[] = UserPermissions::CHANNELS['value'];
        }
        if(MassageUserDealer::where(['uid' => $model->id, 'state' => State::YES['value']])->count()){
            $permissions[] = UserPermissions::DEALER['value'];
        }
        if(MassageUserSalesman::where(['uid' => $model->id, 'state' => State::YES['value']])->count()){
            $permissions[] = UserPermissions::SALESMAN['value'];
        }
        $model->permissions = $permissions;
        # 隐藏手机号中间四位
        if ($model->mobile) {
            $model->mobile = substr_replace($model->mobile, '****', 3, 4);
        }
        $model->is_realname=Examine::NO['value'];
        $MassageUserRealname=MassageUserRealname::where(['uid'=>$model->id,'saas_appid'=>$model->saas_appid])->find();
        if($MassageUserRealname){
            $model->is_realname=$MassageUserRealname->examine;
        }
        return $model;
    }
    public static function getToken($model)
    {
        $data = new \stdClass();
        $data->saas_appid = $model->saas_appid;
        $data->id = $model->id;
        $data->mobile = $model->mobile;
        $data->openid = $model->openid;
        $data->unionid = $model->unionid;
        $data->mp_openid = $model->mp_openid;
        return Auth::setPrefix('Massage')->setExpire(3600 * 24 * 2)->encrypt($data);
    }
    public static function checkWallet($model)
    {
        if (MassageUserWallet::where(['uid' => $model->id])->count()) {
            return true;
        }
        $MassageUserWallet = new MassageUserWallet();
        $MassageUserWallet->saas_appid = $model->saas_appid;
        $MassageUserWallet->uid = $model->id;
        $MassageUserWallet->save();
    }
    public static function NewRegisterGift($UserModel, $pModel)
    {
        $new_user_gift = getHpConfig('', $UserModel->saas_appid, 'new_user_gift');
        if (isset($new_user_gift['new_user_gift_state']) && $new_user_gift['new_user_gift_state']) {
            $MassageCoupon = MassageCoupon::whereIn('id', $new_user_gift['new_user_gift_register'])
                ->field('id')->select();
            foreach ($MassageCoupon as $key => $item) {
                if (in_array('referee', $new_user_gift['new_user_gift_register_role'])) {
                    MassageCouponCode::createAndReceive($item, $pModel);
                }
                if (in_array('referee_user', $new_user_gift['new_user_gift_register_role'])) {
                    MassageCouponCode::createAndReceive($item, $UserModel);
                }
            }
        }
        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $pModel->id, 'examine' => Examine::YES['value']])->find();
        if ($MassageUserTechnician) {
            $new_technicians_gift = getHpConfig('', $UserModel->saas_appid, 'new_technicians_gift');
            if (isset($new_technicians_gift['new_technicians_gift_state']) && $new_technicians_gift['new_technicians_gift_state']) {
                $silver = (int)$new_technicians_gift['new_technicians_gift_register_silver'];
                if ($silver > 0) {
                    $MassageUserTechnician->recommend_silver_num = Db::raw('recommend_silver_num+' . $silver);
                }
                $gold = (int)$new_technicians_gift['new_technicians_gift_register_gold'];
                if ($gold > 0) {
                    $MassageUserTechnician->recommend_gold_num = Db::raw('recommend_gold_num+' . $gold);
                }
                $MassageUserTechnician->save();
            }
        }
    }
    public static function NewFirstOrderGift($UserModel, $pModel)
    {
        $new_user_gift = getHpConfig('', $UserModel->saas_appid, 'new_user_gift');
        if (isset($new_user_gift['new_user_gift_state']) && $new_user_gift['new_user_gift_state']) {
            $MassageCoupon = MassageCoupon::whereIn('id', $new_user_gift['new_user_gift_first_order'])
                ->field('id')->select();
            foreach ($MassageCoupon as $key => $item) {
                if (in_array('referee', $new_user_gift['new_user_gift_first_order_role'])) {
                    MassageCouponCode::createAndReceive($item, $pModel);
                }
                if (in_array('referee_user', $new_user_gift['new_user_gift_first_order_role'])) {
                    MassageCouponCode::createAndReceive($item, $UserModel);
                }
            }
        }

        $MassageUserTechnician = MassageUserTechnician::where(['uid' => $pModel->id, 'examine' => Examine::YES['value']])->find();
        if ($MassageUserTechnician) {
            $new_technicians_gift = getHpConfig('', $UserModel->saas_appid, 'new_technicians_gift');
            if (isset($new_technicians_gift['new_technicians_gift_state']) && $new_technicians_gift['new_technicians_gift_state']) {
                $silver = (int)$new_technicians_gift['new_technicians_gift_first_order_silver'];
                if ($silver > 0) {
                    $MassageUserTechnician->recommend_silver_num = Db::raw('recommend_silver_num+' . $silver);
                }
                $gold = (int)$new_technicians_gift['new_technicians_gift_first_order_gold'];
                if ($gold > 0) {
                    $MassageUserTechnician->recommend_gold_num = Db::raw('recommend_gold_num+' . $gold);
                }
                $MassageUserTechnician->save();
            }
        }
    }
}
